package com.lm.controller;

import com.lm.service.LmTrackEventInfoService;
import com.lm.service.LmTrackEventService;
import com.meirengu.common.StatusCode;
import com.meirengu.controller.BaseController;
import com.meirengu.model.Page;
import com.meirengu.model.Result;
import com.meirengu.utils.NumberUtil;
import com.meirengu.utils.RequestUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * 产品点击事件统计
 *
 * @author Mao
 * @create 2017-05-24 15:58
 */
@Controller
@RequestMapping("event")
public class TrackEventController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(TrackEventController.class);


    @Autowired
    LmTrackEventService lmTrackEventService;

    @Autowired
    LmTrackEventInfoService lmTrackEventInfoService;


    /**
     * 统计产品点击次数
     *
     * @param request
     * @param id       第三方产品id
     * @param userId   用户id
     * @param userName 用户名称
     * @param uuid     前端页面生成的uuid，用于标识唯一用户
     */
    @ResponseBody
    @RequestMapping(method = GET)
    public void trackEvent(HttpServletRequest request,
                           @RequestParam(value = "id", required = false) Integer id,
                           @RequestParam(value = "user_id", required = false) Integer userId,
                           @RequestParam(value = "user_name", required = false) String userName,
                           @RequestParam(value = "cid", required = false) String cid,
                           @RequestParam(value = "mobile", required = false) String mobile,
                           @RequestParam(value = "uuid", required = false) String uuid) {

        HttpSession session = request.getSession();
        String jsessionId = session.getId();

        try {
            if (id == null || id <= 0) {
                return;
            }
            String ip = RequestUtil.getClientIp(request);
            lmTrackEventService.trackEvent(id, ip, userId, userName, cid, mobile, uuid, jsessionId);
        } catch (Exception e) {
            String params = String.format("参数:id:%s,userId:%s,userName:%s,cid:%s,mobile:%s", id, userId, userName, cid, mobile);
            logger.error("TrackEventController trackEvent throws Exceprion :{} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            logger.error(">> trackEvent throw exception: {}", e);
        }
    }

    /**
     * 浏览记录
     *
     * @param userId
     */
    @ResponseBody
    @RequestMapping(value = "list", method = GET)
    public Result getList(@RequestParam(value = "page_num", required = false, defaultValue = "1") Integer pageNum,
                          @RequestParam(value = "page_size", required = false, defaultValue = "10") Integer pageSize,
                          @RequestParam(value = "sortby", required = false, defaultValue = "create_date") String sortBy,
                          @RequestParam(value = "order", required = false, defaultValue = "desc") String order,
                          @RequestParam(value = "user_id", required = false) Integer userId) {
        try {
            if (NumberUtil.isNullOrZero(userId)) {
                return super.setResult(StatusCode.MISSING_ARGUMENT, null, StatusCode.getErrorMsg(StatusCode.MISSING_ARGUMENT));
            }
            Map<String, Object> paramMap = new HashMap<>();
            Page page = super.setPageParams(pageNum, pageSize);
            if (StringUtils.isNotBlank(sortBy)) {
                paramMap.put("sortBy", sortBy);
            }
            if (StringUtils.isNotBlank(order)) {
                paramMap.put("order", order);
            }
            if (!NumberUtil.isNullOrZero(userId)) {
                paramMap.put("userId", userId);
            }
            page = lmTrackEventInfoService.getListById(page, paramMap);
            return super.setResult(StatusCode.OK, page, StatusCode.codeMsgMap.get(StatusCode.OK));
        } catch (Exception e) {
            String params = "";
            logger.error("TrackEventController getList throws Exceprion :{} happens. params:{}.", ExceptionUtils.getFullStackTrace(e), params);
            return setResult(StatusCode.INTERNAL_SERVER_ERROR, null, StatusCode.codeMsgMap.get(StatusCode.INTERNAL_SERVER_ERROR));
        }
    }

}